<?php

namespace app\admin\controller\scanwork;

use app\common\controller\Backend;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 员工基础数据管理
 *
 * @icon fa fa-user
 * @remark 管理员工基础信息，包括技能等级、可操作工序、考勤规则等
 */
class Employee extends Backend
{
    /**
     * Employee模型对象
     * @var \app\admin\model\scanwork\Employee
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\scanwork\Employee;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("skillLevelList", $this->model->getSkillLevelList());
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['user'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            // 添加工作量统计信息
            $rows = [];
            foreach ($list as $item) {
                $row = $item->toArray();
                try {
                    $workload = $item->getCurrentWorkload();
                    $row['current_tasks'] = $workload['current_tasks'] ?? 0;
                    $row['remaining_quantity'] = $workload['remaining_quantity'] ?? 0;
                } catch (Exception $e) {
                    $row['current_tasks'] = 0;
                    $row['remaining_quantity'] = 0;
                }
                $rows[] = $row;
            }

            $result = array("total" => $list->total(), "rows" => $rows);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        // 获取系统用户列表（未关联的员工）
        $linkedUserIds = $this->model->column('user_id');
        $userList = \app\common\model\User::where('status', 'normal')
            ->where('id', 'not in', $linkedUserIds)
            ->column('nickname', 'id');
        $this->view->assign('userList', $userList);
        
        // 获取工序列表
        $processList = \app\admin\model\scanwork\Process::where('status', 1)->column('name', 'id');
        $this->view->assign('processList', $processList);

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                // 生成员工编码
                if (empty($params['employee_code'])) {
                    $params['employee_code'] = $this->generateEmployeeCode();
                }
                
                // 检查员工编码是否唯一
                if (!$this->model->checkCodeUnique($params['employee_code'])) {
                    $this->error('员工编码已存在');
                }
                
                // 检查用户ID是否唯一
                if (!$this->model->checkUserIdUnique($params['user_id'])) {
                    $this->error('该用户已关联其他员工');
                }

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            } else {
                $this->error(__('Parameter %s can not be empty', ''));
            }
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        // 获取系统用户列表（包括当前用户）
        $linkedUserIds = $this->model->where('id', '<>', $ids)->column('user_id');
        $userList = \app\common\model\User::where('status', 'normal')
            ->where('id', 'not in', $linkedUserIds)
            ->column('nickname', 'id');
        $this->view->assign('userList', $userList);
        
        // 获取工序列表
        $processList = \app\admin\model\scanwork\Process::where('status', 1)->column('name', 'id');
        $this->view->assign('processList', $processList);
        
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                // 检查员工编码是否唯一
                if (!$this->model->checkCodeUnique($params['employee_code'], $ids)) {
                    $this->error('员工编码已存在');
                }
                
                // 检查用户ID是否唯一
                if (!$this->model->checkUserIdUnique($params['user_id'], $ids)) {
                    $this->error('该用户已关联其他员工');
                }
                
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $name;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            } else {
                $this->error(__('Parameter %s can not be empty', ''));
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $item) {
                    // 检查是否有关联的分工分配
                    $allocationCount = \app\admin\model\scanwork\Allocation::where('user_id', $item->user_id)->count();
                    if ($allocationCount > 0) {
                        throw new Exception("员工【{$item->employee_name}】下还有{$allocationCount}个分工分配，请先删除相关分工");
                    }
                    
                    $count += $item->delete();
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        } else {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
    }

    /**
     * 查看详情
     */
    public function detail($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        // 获取工作量统计
        $workloadStats = $row->getWorkloadStats();
        
        // 获取工资统计
        $wageStats = $row->getWageStats();
        
        // 获取当前工作负荷
        $currentWorkload = $row->getCurrentWorkload();
        
        // 获取可操作工序
        $matchingProcesses = $row->getMatchingProcesses();
        
        // 获取最近的分工分配
        $recentAllocations = \app\admin\model\scanwork\Allocation::with(['order', 'model.product', 'process'])
            ->where('user_id', $row->user_id)
            ->order('createtime desc')
            ->limit(10)
            ->select();
        
        // 获取最近的报工记录
        $recentReports = \app\admin\model\scanwork\Report::with(['allocation.order', 'allocation.process'])
            ->where('user_id', $row->user_id)
            ->order('createtime desc')
            ->limit(10)
            ->select();
        
        $this->view->assign('row', $row);
        $this->view->assign('workloadStats', $workloadStats);
        $this->view->assign('wageStats', $wageStats);
        $this->view->assign('currentWorkload', $currentWorkload);
        $this->view->assign('matchingProcesses', $matchingProcesses);
        $this->view->assign('recentAllocations', $recentAllocations);
        $this->view->assign('recentReports', $recentReports);
        
        return $this->view->fetch();
    }

    /**
     * 生成员工编码
     */
    private function generateEmployeeCode()
    {
        $prefix = 'RY-' . date('Y') . '-';
        $lastCode = $this->model->where('employee_code', 'like', $prefix . '%')
            ->order('employee_code desc')
            ->value('employee_code');
        
        if ($lastCode) {
            $lastNumber = intval(substr($lastCode, -3));
            $newNumber = $lastNumber + 1;
        } else {
            $newNumber = 1;
        }
        
        return $prefix . str_pad($newNumber, 3, '0', STR_PAD_LEFT);
    }

    /**
     * 获取员工列表（用于下拉选择）
     */
    public function getEmployeeList()
    {
        $list = $this->model->where('status', 1)->column('employee_name', 'user_id');
        $this->success('', null, $list);
    }

    /**
     * 更新员工技能等级
     */
    public function updateSkillLevel()
    {
        $ids = $this->request->post('ids');
        $skillLevel = $this->request->post('skill_level');
        
        if (!$ids || !$skillLevel) {
            $this->error('参数错误');
        }
        
        $validLevels = array_keys($this->model->getSkillLevelList());
        if (!in_array($skillLevel, $validLevels)) {
            $this->error('无效的技能等级');
        }
        
        try {
            $count = $this->model->where('id', 'in', $ids)->update(['skill_level' => $skillLevel]);
            $this->success("成功更新{$count}个员工的技能等级");
        } catch (Exception $e) {
            $this->error('更新失败：' . $e->getMessage());
        }
    }

    /**
     * 管理员工可操作工序
     */
    public function manageProcesses($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        // 获取所有工序
        $allProcesses = \app\admin\model\scanwork\Process::where('status', 1)->select();
        $this->view->assign('allProcesses', $allProcesses);
        
        if ($this->request->isPost()) {
            $processIds = $this->request->post('process_ids', []);
            
            try {
                $row->save(['operable_processes' => $processIds]);
                $this->success('可操作工序更新成功');
            } catch (Exception $e) {
                $this->error('更新失败：' . $e->getMessage());
            }
        }
        
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    /**
     * 获取员工工作量统计
     */
    public function getWorkloadStats()
    {
        $ids = $this->request->get('ids');
        $startDate = $this->request->get('start_date');
        $endDate = $this->request->get('end_date');
        
        if (!$ids) {
            $this->error('参数错误');
        }
        
        $employee = $this->model->get($ids);
        if (!$employee) {
            $this->error('员工不存在');
        }
        
        $stats = $employee->getWorkloadStats($startDate, $endDate);
        $this->success('', null, $stats);
    }

    /**
     * 获取员工工资统计
     */
    public function getWageStats()
    {
        $ids = $this->request->get('ids');
        $startDate = $this->request->get('start_date');
        $endDate = $this->request->get('end_date');
        
        if (!$ids) {
            $this->error('参数错误');
        }
        
        $employee = $this->model->get($ids);
        if (!$employee) {
            $this->error('员工不存在');
        }
        
        $stats = $employee->getWageStats($startDate, $endDate);
        $this->success('', null, $stats);
    }

    /**
     * 批量导入员工
     */
    public function import()
    {
        if ($this->request->isPost()) {
            $file = $this->request->file('file');
            if (!$file) {
                $this->error('请选择文件');
            }
            
            $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);
            if (!in_array($ext, ['xlsx', 'xls'])) {
                $this->error('文件格式错误，请上传Excel文件');
            }
            
            try {
                // 使用PhpSpreadsheet读取Excel
                $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file->getPathname());
                $worksheet = $spreadsheet->getActiveSheet();
                $data = $worksheet->toArray();
                
                // 过滤空行
                $validData = [];
                foreach ($data as $row) {
                    if (!empty(array_filter($row, function($cell) { return !is_null($cell) && $cell !== ''; }))) {
                        $validData[] = $row;
                    }
                }
                
                if (count($validData) < 2) {
                    $this->error('Excel文件数据不足');
                }
                
                $successCount = 0;
                $errorCount = 0;
                $errors = [];
                
                Db::startTrans();
                try {
                    // 从第二行开始处理数据（第一行是标题）
                    for ($i = 1; $i < count($validData); $i++) {
                        $row = $validData[$i];
                        
                        if (empty($row[0]) || empty($row[1])) { // 员工姓名和用户名不能为空
                            $errorCount++;
                            $errors[] = "第" . ($i + 1) . "行：员工姓名和用户名不能为空";
                            continue;
                        }
                        
                        // 查找系统用户
                        $user = \app\common\model\User::where('username', trim($row[1]))->find();
                        if (!$user) {
                            $errorCount++;
                            $errors[] = "第" . ($i + 1) . "行：用户名【{$row[1]}】不存在";
                            continue;
                        }
                        
                        // 检查用户是否已关联员工
                        if ($this->model->where('user_id', $user->id)->find()) {
                            $errorCount++;
                            $errors[] = "第" . ($i + 1) . "行：用户【{$row[1]}】已关联其他员工";
                            continue;
                        }
                        
                        $employeeData = [
                            'employee_name' => trim($row[0]),
                            'user_id' => $user->id,
                            'position' => isset($row[2]) ? trim($row[2]) : '',
                            'skill_level' => isset($row[3]) ? trim($row[3]) : 'basic',
                            'contact_phone' => isset($row[4]) ? trim($row[4]) : '',
                            'hire_date' => isset($row[5]) ? trim($row[5]) : null,
                            'default_hourly_rate' => isset($row[6]) ? floatval($row[6]) : 0,
                            'status' => 1,
                            'createtime' => time()
                        ];
                        
                        // 生成员工编码
                        $employeeData['employee_code'] = $this->generateEmployeeCode();
                        
                        $this->model->create($employeeData);
                        $successCount++;
                    }
                    
                    Db::commit();
                    $message = "导入完成！成功：{$successCount}条，失败：{$errorCount}条";
                    if (!empty($errors)) {
                        $message .= "\n错误详情：\n" . implode("\n", $errors);
                    }
                    $this->success($message);
                    
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error('导入失败：' . $e->getMessage());
                }
                
            } catch (Exception $e) {
                $this->error('文件读取失败：' . $e->getMessage());
            }
        }
        
        return $this->view->fetch();
    }

    /**
     * 下载导入模板
     */
    public function downloadTemplate()
    {
        try {
            $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
            $sheet = $spreadsheet->getActiveSheet();
            
            // 设置标题
            $sheet->setCellValue('A1', '员工信息导入模板');
            $sheet->mergeCells('A1:H1');
            
            // 设置表头
            $sheet->setCellValue('A2', '员工姓名*');
            $sheet->setCellValue('B2', '用户名*');
            $sheet->setCellValue('C2', '生产岗位');
            $sheet->setCellValue('D2', '技能等级');
            $sheet->setCellValue('E2', '联系电话');
            $sheet->setCellValue('F2', '入职日期');
            $sheet->setCellValue('G2', '默认工时单价');
            $sheet->setCellValue('H2', '备注');
            
            // 设置示例数据
            $sheet->setCellValue('A3', '王师傅');
            $sheet->setCellValue('B3', 'wangshifu');
            $sheet->setCellValue('C3', '焊工');
            $sheet->setCellValue('D3', 'advanced');
            $sheet->setCellValue('E3', '13800138003');
            $sheet->setCellValue('F3', '2024-01-15');
            $sheet->setCellValue('G3', '25.00');
            $sheet->setCellValue('H3', '高级焊工');
            
            // 设置列宽
            $sheet->getColumnDimension('A')->setWidth(15);
            $sheet->getColumnDimension('B')->setWidth(15);
            $sheet->getColumnDimension('C')->setWidth(15);
            $sheet->getColumnDimension('D')->setWidth(15);
            $sheet->getColumnDimension('E')->setWidth(15);
            $sheet->getColumnDimension('F')->setWidth(15);
            $sheet->getColumnDimension('G')->setWidth(15);
            $sheet->getColumnDimension('H')->setWidth(20);
            
            // 设置样式
            $sheet->getStyle('A1:H1')->getFont()->setBold(true)->setSize(14);
            $sheet->getStyle('A2:H2')->getFont()->setBold(true);
            $sheet->getStyle('A2:H2')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
            
            // 设置边框
            $sheet->getStyle('A2:H3')->getBorders()->getAllBorders()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN);
            
            // 输出文件
            $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
            $filename = '员工信息导入模板_' . date('YmdHis') . '.xlsx';
            
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="' . $filename . '"');
            header('Cache-Control: max-age=0');
            
            $writer->save('php://output');
            exit;
            
        } catch (Exception $e) {
            $this->error('模板生成失败：' . $e->getMessage());
        }
    }

    /**
     * 员工工作负荷统计
     */
    public function workload()
    {
        try {
            // 获取所有用户的工作负荷数据
            $users = \app\common\model\User::where('status', 'normal')->select();
            $workloadList = [];
            $normalCount = 0;
            $highCount = 0;
            $overloadCount = 0;
            $skillStats = [
                'basic' => 0,
                'intermediate' => 0,
                'advanced' => 0
            ];

            foreach ($users as $user) {
                // 获取用户的分工分配统计
                $totalAllocations = \app\admin\model\scanwork\Allocation::where('user_id', $user->id)->count();
                $completedAllocations = \app\admin\model\scanwork\Allocation::where('user_id', $user->id)
                    ->where('status', 1)->count();
                $pendingAllocations = $totalAllocations - $completedAllocations;

                // 计算工作负荷率
                $workloadRate = $totalAllocations > 0 ? round(($completedAllocations / $totalAllocations) * 100, 1) : 0;

                // 统计负荷分布
                if ($workloadRate >= 80) {
                    $normalCount++;
                } elseif ($workloadRate >= 60) {
                    $highCount++;
                } else {
                    $overloadCount++;
                }

                // 获取最后报工时间
                $lastReport = \app\admin\model\scanwork\Report::where('user_id', $user->id)
                    ->order('createtime desc')->find();
                $lastReportTime = $lastReport ? (int)$lastReport->createtime : null;

                $workloadList[] = [
                    'user_id' => $user->id,
                    'nickname' => $user->nickname,
                    'username' => $user->username,
                    'total_allocations' => $totalAllocations,
                    'completed_allocations' => $completedAllocations,
                    'pending_allocations' => $pendingAllocations,
                    'workload_rate' => $workloadRate,
                    'last_report_time' => $lastReportTime
                ];
            }

            // 计算技能等级百分比
            $totalUsers = count($users);
            if ($totalUsers > 0) {
                $skillStats['basic_percent'] = round(($skillStats['basic'] / $totalUsers) * 100, 1);
                $skillStats['intermediate_percent'] = round(($skillStats['intermediate'] / $totalUsers) * 100, 1);
                $skillStats['advanced_percent'] = round(($skillStats['advanced'] / $totalUsers) * 100, 1);
            } else {
                $skillStats['basic_percent'] = 0;
                $skillStats['intermediate_percent'] = 0;
                $skillStats['advanced_percent'] = 0;
            }

            $this->view->assign('workloadList', $workloadList);
            $this->view->assign('normalCount', $normalCount);
            $this->view->assign('highCount', $highCount);
            $this->view->assign('overloadCount', $overloadCount);
            $this->view->assign('skillStats', $skillStats);

            return $this->view->fetch();

        } catch (Exception $e) {
            $this->error('获取工作负荷数据失败：' . $e->getMessage());
        }
    }
}
